<?php

/**
 * @package Core
 * @author superx
 */
class Core_ArrayObject implements ArrayAccess {

    public function __construct($data = null) {
        if ($data) {
            $this->fromArray($data);
        }
    }

    public function fromArray($array) {
        $ref = new ReflectionObject($this);
        $props = $ref->getProperties(ReflectionProperty::IS_PUBLIC);
        foreach ($props as $prop) {
            if (isset($array[$prop->name])) {
                $this->{$prop->name} = $array[$prop->name];
            }
        }
        return true;
    }

    public function toArray() {
        $ref = new ReflectionObject($this);
        $props = $ref->getProperties(ReflectionProperty::IS_PUBLIC);
        $ret = array();
        foreach ($props as $prop) {
            $ret[$prop->name] = $this[$prop->name];
        }
        return $ret;
    }

    /****************************************************
     * Realize ArrayAccess Interface
     ****************************************************/

    /**
     * @param mixed $index
     * @return bool
     */
    public function offsetExists($index) {
        return property_exists($this, $index);
    }

    public function offsetGet($index) {
        return $this->$index;
    }

    public function offsetSet($index, $value) {
        $this->$index = $value;
    }

    public function offsetUnset($index) {
        unset($this->$index);
    }

}
